﻿var PageSize = 20;
var grid = null;
var url = "RoleInf.aspx?";
var permission = null;
var form = null;

$(document).ready(function () {
    permission = JSON.parse($("#hdPermission").val());

    grid = $("#maingrid").ligerGrid({
        columns: [
            { display: '角色ID', name: 'RoleID', width: 100, align: 'left' },
            { display: '角色描述', name: 'RoleDesc', width: 200, align: 'left' },
            { display: '更新时间', name: 'Lpt', width: 200, align: 'center', isSort: false },
            { display: '操作者', name: 'Whom', width: 100, align: 'left' }
            ],
        pageSize: PageSize, toolbar: {}, url: url + "Action=GetList", width: '100%', height: '99%', dataAction: 'server', pageSizeOptions: [3,20, 25, 30, 35], checkbox: true,
        pageStatMessage: 'Record:{from}-{to} Total:{total} Page Size:{pagesize}',
        rowAttrRender: function (item, rowid) {
            var color = "";
            if (item.Flag == "I") {
                color = " my-disabled";
            }
            return color; 
        },
        onDblClickRow: function (row, rowindex, rowDomElement) {
            if (permission.isEdit) {
                showDetail({ RID: row.RID,
                    RoleID: row.RoleID,
                    RoleDesc: row.RoleDesc
                });
            }
        }
    });

    //加载搜索框
    InitForm();

    //加载工具条
    loadToolbar();
    //    if (permission.isEnquiry) {
    //        $("#BtnSearch").removeAttr("disabled");
    //    } else {
    //        $("#BtnSearch").attr("disabled", "disabled");
    //    }
})

//工具条
function loadToolbar() {
    var griditems = [];
    if (permission.isEdit) 
        griditems[griditems.length] = { click: toolbarClick, text: "新增", img: "../images/add.png", id: "Add" };
    if (permission.isActive) 
        griditems[griditems.length] = { click: toolbarClick, text: "生效", img: "../images/Active.png", id: "Enable" };
    if (permission.isInactive)
        griditems[griditems.length] = { click: toolbarClick, text: "失效", img: "../images/Frozen.png", id: "Disable" };
    grid.toolbarManager.set('items', griditems);
}

//搜索框
function InitForm() {
    $("#txtRoleID").ligerTextBox({ label: "角色ID", labelWidth: 80 });
    $("#txtRlName").ligerTextBox({ label: '角色描述', labelWidth: 80 });
    $("#BtnSearch").click(function () { BtnSearch_Click(); });
}


//工具条事件
function toolbarClick(item) {
    switch (item.id) {
        case "Add": BtnAdd_Click(); break;
        case "Enable": BtnEnable_Click(); break;
        case "Disable": BtnDisable_Click(); break;
    }
}

//查询
function BtnSearch_Click() {
    var txtRoleID = $("#txtRoleID").val();
    var txtRlName = $("#txtRlName").val();
    grid.set('parms', { roleID: txtRoleID, roleDesc: txtRlName });
    grid.options.newPage = 1;
    grid.loadData();
}

//Add
function BtnAdd_Click() { showDetail({ RID: '' }, true); }

//Enable
function BtnEnable_Click() { ProcessData("A"); }

//Disable
function BtnDisable_Click() { ProcessData("I"); }

function ProcessData(flag) {
    var rids = GetClientRID();
    if (rids != "") {
        $.ajax({
            type: 'post', url: url + 'Action=Process&flag=' + flag + '&rids=' + rids, dataType: 'text', cache: false,
            success: function (msg) { if (msg == "") { toastrSuccess("Processed successfully/处理成功!"); BtnSearch_Click(); } else { toastrError("Processed Failed/处理失败!<br/>" + msg) } },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                ShowError("ProcessData()", XMLHttpRequest, textStatus, errorThrown);
            }
        });
    }
}

//获取选中列表ID
function GetClientRID() {
    var rows = grid.getSelectedRows();
    if (!rows.length) { toastrWarning('Please select lines to be processed!<br/>请选择操作记录!'); return ""; }
    var ids = [];
    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i].RID);
    }
    return ids.join(',');
}


////////////////////////////////////////////
//新增、编辑框
var detailWin = null, curentData = null;

function showDetail(data) {
    curentData = data;
    if (detailWin) {
        detailWin.show();
    }
    else {
        //创建表单结构
        var mainform = $("#mainform");
        form=mainform.ligerForm({
            inputWidth: 280,
            fields: [
         { name: "RID", type: "hidden" },
         { display: "角色ID", name: "RoleID", newline: true, labelWidth: 150, width: 220, space: 30, type: "text" },
         { display: "角色描述", name: "RoleDesc", newline: true, labelWidth: 150, width: 220, space: 30, type: "text" }
         ]
        });


        detailWin = $.ligerDialog.open({
            title: "角色管理", target: $("#detail"), width: 450, height: 200, top: 120, allowClose: false,
            buttons: [
                  { text: '保存', onclick: function () { save(); } },
                  { text: '取消', onclick: function () { detailWin.hide(); HideTip(); } }
                  ]
        });
    }
    if (curentData.RID != '') {
        $("#RID").val(curentData.RID);
        $("#RoleID").val(curentData.RoleID);
        $("#RoleID").ligerGetTextBoxManager().setDisabled();
        $("#RoleDesc").val(curentData.RoleDesc);


    } else {
        $("#RID").val('');
        $("#RoleID").val('');
        $("#RoleID").ligerGetTextBoxManager().setEnabled();
        $("#RoleDesc").val('');

    }
    //$("#croleID").attr("maxlength", 20);
    //$("#croleDesc").attr("maxlength", 40);

    function save() {
        HideTip();
        curentData = curentData || {};
        //curentData.RID = form.getData().RID;
        //curentData.RoleID = $.trim(form.getData().RoleID);
        curentData.RID = $("#RID").val();

        curentData.RoleID = $("#RoleID").val();
        if (curentData.RoleID == "") {
            showErrTip('RoleID', "Empty is not allowed/不能为空!");
            return false;
        }
        if (curentData.RoleID.length > 20) {
            showErrTip('RoleID', 'Must be less than 20 characters/必须少于20个字符!');
            return false;
        }

        //curentData.RoleDesc = $.trim(form.getData().RoleDesc);
        curentData.RoleDesc = $("#RoleDesc").val();
        if (curentData.RoleDesc == "") {
            showErrTip('RoleDesc', "Empty is not allowed/不能为空!");
            return false;
        }
        if (curentData.RoleDesc.length > 40) {
            showErrTip('RoleDesc', 'Must be less than 40 characters/必须少于40个字符!');
            return false;
        }

        var _url = url + "Action=Save";
        $.ajax({
            cache: false,
            async: true,
            url: _url,
            data: curentData,
            dataType: 'text',
            type: 'post',
            success: function (res) {
                grid.loadData();
                switch (res) {
                    case "existed":
                        toastrWarning('Role ID is already exists, please try another!<br/>角色代码已经存在,请重新输入!');
                        break;
                    case "":
                        toastrSuccess('Saved/保存成功!');
                        detailWin.hide();
                        break;
                    default:
                        toastrError(res);
                        break;
                }
            },
            error: function (message) {
                if (message.responseText == "True") {
                    grid.loadData();
                    toastrSuccess('Saved/保存成功!');
                    detailWin.hide();
                } else {
                    toastrError('Error! Not saved/保存失败!');
                }
            }
        });
    }

    
}
/////////////////////////////////////////////////////////
function showErrTip(id, err) {
    $('#' + id).ligerTip({ content: err }); $('#' + id).select(); return false;
}
function HideTip() { $("#RoleID").ligerHideTip(); $("#RoleDesc").ligerHideTip(); }

function ShowError(fun, XMLHttpRequest, textStatus, errorThrown) {
    var mess = "出错了! 请联系管理员!<br/>";
    mess += "function:" + fun + "<br/>";
    mess += "XMLHttpRequest.status:" + XMLHttpRequest.status + "<br/>";
    mess += "XMLHttpRequest.readyState:" + XMLHttpRequest.readyState + "<br/>";
    mess += "textStatus:" + textStatus;
    toastrError(mess);
}
